using UnityEngine;

namespace Galplay {
  public enum MainMenuType {
    Game,
    Chapter,
  }

  public class MenuManager : MonoBehaviour {
    [Tooltip("当前显示的类型")]
    public MainMenuType menuType = MainMenuType.Game;
    [Tooltip("用于放置项目的容器")]
    public Transform scrollContent;
    [Tooltip("用于载入Button的Prefab")]
    public GameObject buttonPrefab;
    [Tooltip("用于按钮的AudioSource")]
    public AudioSource audioSource;

    private GameManager GM { get => GameManager.Instance; }

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start() {

    }

    // Update is called once per frame
    void Update() {

    }



    public void ToggleGames() {
      if (OpenIfNotExist(MainMenuType.Game)) {
        LoadGames();
      }
    }

    public void ToggleChapters() {
      if (OpenIfNotExist(MainMenuType.Chapter)) {
        LoadChapters();
      }
    }

    private bool OpenIfNotExist(MainMenuType type) {
      if (menuType == type) {
        if (gameObject.activeSelf) {
          CloseMenu();
          return false;
        }
      }

      OpenMenu();
      return true;
    }

    public void LoadGames() {
      menuType = MainMenuType.Game;
      ClearContent();


      foreach (var game in ProjectManager.Instance.Games) {
        var obj = Instantiate(buttonPrefab, scrollContent.transform);
        var btn = obj.GetComponent<ChapterButton>();
        btn.title.text = game.Name;
        btn.game = game;
        btn.sound.audioObject = audioSource;
        btn.sound.enabled = true;
        GameManager.SetImage(btn.icon, game.TitleIconFullPath);
      }
    }

    public void LoadChapters() {
      menuType = MainMenuType.Chapter;
      ClearContent();

      foreach (var chapter in GM.Game.Scenes) {
        var obj = Instantiate(buttonPrefab, scrollContent.transform);
        var btn = obj.GetComponent<ChapterButton>();
        btn.title.text = chapter.Name;
        btn.scene = chapter;
        btn.sound.audioObject = audioSource;
        btn.sound.enabled = true;
        GM.SetImageAsset(btn.icon, chapter.Icon);
      }
    }

    private void ClearContent() {
      foreach (Transform child in scrollContent.transform) {
        Destroy(child.gameObject);
      }
    }

    public void CloseMenu() {
      gameObject.SetActive(false);
    }

    public void OpenMenu() {
      gameObject.SetActive(true);
    }

  }

}